<?php
/*
 * @Author: lokei
 * @Date: 2022-08-20 17:03:15
 * @LastEditors: lokei
 * @LastEditTime: 2022-09-19 12:49:30
 * @Description: 
 */

namespace App\Http\Controllers\Scrm\Qiwei;

use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Scrm\Qiwei\Common;
use App\Models\Scrm\Clerk\ClerkModel;
use App\Models\Scrm\Department\DepartmentModel;
use GuzzleHttp;
use Illuminate\Http\Request;

class ClerkController extends Controller
{

    public function sync()
    {
        $http = new GuzzleHttp\Client;
        $params = [
            'access_token' => Common::getAccessToken()
        ];
        $response = $http->get('https://qyapi.weixin.qq.com/cgi-bin/user/list_id', [
            'query' => $params
        ]);
        $result = json_decode($response->getBody(), true);
        if (array_key_exists('errcode', $result) && $result['errcode'] != 0) {
            $res = ResultTool::fail();
            $res['errorCode'] = $result['errcode'];
            $res['errorMsg'] = $result['errmsg'];
            return $res;
        } else {
            $dept_user = $result['dept_user'];
            foreach ($dept_user as $qw_user) {
                $clerk = ClerkModel::where('qw_userid', '=', $qw_user['userid'])->where('qw_department_id', '=', $qw_user['department'])->first();
                if(is_null($clerk)) {
                    $clerk = new ClerkModel();
                    $clerk->qw_userid = $qw_user['userid'];
                    $clerk->qw_department_id = $qw_user['department'];
                    $department = DepartmentModel::where('qw_id', '=', $qw_user['department'])->first();
                    if(!is_null($department)) {
                        $clerk->department_id = $department->id;
                    }
                    $clerk->save();
                }
            }
        }
        return ResultTool::success();
    }
    
    public function update(Request $request)
    {
        $http = new GuzzleHttp\Client;
        $clerk = ClerkModel::where('id', '=', $request->input('id'))->first();
        $params = [
            'userid' => $clerk->qw_userid,
            'name' => $request->input('name')
        ];
        $response = $http->POST('https://qyapi.weixin.qq.com/cgi-bin/user/update', [
            'query' => [
                'access_token' => Common::getAccessToken()
            ],
            'json' => $params
        ]);
        $result = json_decode($response->getBody(), true);
        if (array_key_exists('errcode', $result) && $result['errcode'] != 0) {
            $res = ResultTool::fail();
            $res['errorCode'] = $result['errcode'];
            $res['errorMsg'] = $result['errmsg'];
            return $res;
        } else {
            $clerk->name = $request->input('name');
            $clerk->save();
        }
        return ResultTool::success();
    }

}
